/**
 * e-fuli.com Inc.
 * Copyright (c) 2015-2018 All Rights Reserved.
 */
package tools;

import org.apache.commons.codec.binary.Base64;

import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * <pre>
 * MD5Util
 * </pre>
 *
 * @author jimmy
 * @version $Id: MD5Util.java, v 0.1 2018年1月18日 下午2:34:44 jimmy Exp $
 */
public final class MD5Util {

    private MD5Util() {

    }

    public static String md5(String data) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            return byteToHexString(md.digest(data.getBytes("UTF-8")));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    private static String byteToHexString(byte[] b) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            hexString.append(hex.toLowerCase());
        }
        return hexString.toString();
    }

    public static String getContentMD5(String filePath) {
        // 获取文件MD5的二进制数组（128位）
        byte[] bytes = getFileMD5Bytes128(filePath);
        // 对文件MD5的二进制数组进行base64编码（而不是对32位的16进制字符串进行编码）
        return new String(Base64.encodeBase64(bytes));
    }

    /***
     * 获取文件MD5-二进制数组（128位）
     *
     * @param filePath
     * @return
     * @throws java.io.IOException
     */
    public static byte[] getFileMD5Bytes128(String filePath) {
        FileInputStream fis = null;
        byte[] md5Bytes = null;
        try {
            File file = new File(filePath);
            fis = new FileInputStream(file);
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[1024];
            int length = -1;
            while ((length = fis.read(buffer, 0, 1024)) != -1) {
                md5.update(buffer, 0, length);
            }
            md5Bytes = md5.digest();
            fis.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return md5Bytes;
    }

    public boolean validToken(String requestId, String key, String token){
        boolean valid = false;
//        if (StringUtil.isBlank(requestId) || StringUtil.isBlank(key) || StringUtil.isBlank(token)) {
//            return false;
//        }
//        if(this.md5(requestId + key).equals(token)) {
//            return true;
//        }
        return valid;

    }

}
